package com.jxs.android.ges;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.xmlpull.v1.XmlPullParserException;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;

import com.jxs.android.ges.data.ContactInfo;
import com.jxs.android.soap.BuWebService;
import com.jxs.android.soap.IWebService;
import com.jxs.android.soap.SoapUtil;
import com.jxs.android.util.MemoryUtil;
import com.jxs.android.weiget.BuLoadingDailog;
import com.jxs.android.weiget.TopBar;

@SuppressLint("HandlerLeak")
public class WorkLogGetSystemContactList extends AbstractActivity {
	// 2.4.6 getSystemContactList 【获取发送页面内容】
	private BuLoadingDailog progressDialog;
	private ListView phone_list;
	private CheckBox checked_all, un_checked_all;
	private Button sure_ok;
	private Context context;
	private List<ContactInfo> contactInfos = new ArrayList<ContactInfo>();
	private ContactSelectAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		context = this;
		initTopBar(savedInstanceState, R.layout.bu_work_log_get_sys_contact_list);
		phone_list = (ListView) findViewById(R.id.phone_list);
		adapter = new ContactSelectAdapter(contactInfos);
		phone_list.setAdapter(adapter);

		checked_all = (CheckBox) findViewById(R.id.checked_all);
		un_checked_all = (CheckBox) findViewById(R.id.un_checked_all);
		sure_ok = (Button) findViewById(R.id.sure_ok);

		checked_all.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				adapter.checkedAll();
				checked_all.setChecked(true);
				un_checked_all.setChecked(false);
			}
		});
		un_checked_all.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				checked_all.setChecked(false);
				un_checked_all.setChecked(true);
				adapter.unCheckedAll();
			}
		});

		sure_ok.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				Bundle bundle = new Bundle();
				bundle.putStringArrayList("phones", adapter.getCheckedPhones());
				intent.putExtras(bundle);
				setResult(RESULT_OK, intent);
				finish();
			}
		});

		getSystemContactList();
	}

	@Override
	public void topBarLogic(TopBar topBar) {
		super.topBarReturn(topBar);
		topBar.setTitle("号码选择");
		topBar.showLogicBtn();
		topBar.hindFilter();
		topBar.hindSpinnerBtn();
		topBar.hindLogicBtn();
	}

	private void getSystemContactList() {
		progressDialog = new BuLoadingDailog(this);
		progressDialog.showLoading(R.string.load_and_wait);
		new Thread(new Runnable() {
			@Override
			public void run() {
				getSystemContactList(GesApplication.getUserInfo().getTicket());
			}
		}).start();
	}

	// 2.4.7 getSystemContactList 【获取系统内部人员号码列表】
	private void getSystemContactList(String ticket) {
		// 2.4.3 getSystemContactList 【获取工作日志详单接口】
		String wsdl_url = GesApplication.WSDL_URL;// wsdl
		String namespace = GesApplication.WSDL_NAME_SPACE;// namespace
		String methodName = "getSystemContactList";// 要调用的方法名称
		SoapObject request = new SoapObject(namespace, methodName);
		request.addProperty("ticket", ticket);
		BuWebService webService = new BuWebService(wsdl_url, request);
		webService.setDoNet(false);
		webService.requestWSDL(new IWebService() {
			@Override
			public void logic(SoapSerializationEnvelope envelope) throws IOException, XmlPullParserException {
				SoapObject response = (SoapObject) envelope.getResponse();
				paser(response);
			}

			@Override
			public void error(String message, Exception e) {
				Message msg = new Message();
				msg.what = ERROR_MSG;
				msg.obj = message;
				handler.sendMessage(msg);
			}

		});
	}

	private void paser(SoapObject soapObject) {
		if (null != soapObject) {
			String stauts = soapObject.getProperty("status").toString();
			SoapObject msgObjec = (SoapObject) soapObject.getProperty("msg");
			String message = msgObjec.getProperty("message").toString();
			if ("-2".equals(stauts)) {
				Message msg = new Message();
				msg.what = ERROR_MSG;
				msg.obj = message;
				handler.sendMessage(msg);
			} else if ("-1".equals(stauts)) {
				Message msg = new Message();
				msg.what = TO_LOGIN;
				msg.obj = message;
				handler.sendMessage(msg);
			} else if ("0".equals(stauts)) {
				Message msg = new Message();
				msg.what = UPDATE_LIST_UI;
				msg.obj = (SoapObject) soapObject.getProperty("retMsg");
				handler.sendMessage(msg);
			}
		}
	}

	private final int UPDATE_LIST_UI = 0x101;
	private final int ERROR_MSG = 0x1013;
	private final int TO_LOGIN = 0x1019;
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {

			if (!MemoryUtil.isCurrentActivity(WorkLogGetSystemContactList.class)) {
				return;
			}

			if (null != progressDialog && progressDialog.isShowing()) {
				progressDialog.dismiss();
			}
			if (msg.what == UPDATE_LIST_UI) {
				initContactList((SoapObject) msg.obj);
			} else if (msg.what == ERROR_MSG) {
				errorMsgPop(msg.obj.toString());
			} else if (msg.what == TO_LOGIN) {
				errorMsgToLogin(msg.obj.toString());
			}
		}
	};

	private void initContactList(SoapObject retMsgObject) {
		if (null != retMsgObject) {
			for (int i = 0; i < retMsgObject.getPropertyCount(); i++) {
				SoapObject taskBeanObject = (SoapObject) retMsgObject.getProperty(i);
				ContactInfo contactInfo = new ContactInfo();
				contactInfo.cust_manager_name = SoapUtil.getValue(taskBeanObject, "cust_manager_name");
				contactInfo.industry_type_name = SoapUtil.getValue(taskBeanObject, "industry_type_name");
				contactInfo.phone_no = SoapUtil.getValue(taskBeanObject, "phone_no");
				contactInfos.add(contactInfo);
			}
		}
		adapter.setContacts(contactInfos);
		adapter.notifyDataSetChanged();

	}

	private class ContactSelectAdapter extends BaseAdapter {

		class ViewHolder {
			TextView industry_type_name;// :所属行业
			TextView cust_manager_name;// :名称
			TextView phone_no;// ：手机号码
			CheckBox select_box; // 选中的条目

		}

		private List<ContactInfo> contacts;

		private LayoutInflater inflater = null;
		private ViewHolder holder = null;

		public void setContacts(List<ContactInfo> contacts) {
			this.contacts = contacts;
		}

		public ArrayList<String> getCheckedPhones() {
			ArrayList<String> rs = new ArrayList<String>();
			for (ContactInfo msg : contacts) {
				if (msg.isSelected) {
					rs.add(msg.phone_no);
				}
			}
			return rs;
		}

		public ContactSelectAdapter(List<ContactInfo> contactInfos) {
			inflater = LayoutInflater.from(context);
			this.contacts = contactInfos;
		}

		public void checkedAll() {
			for (ContactInfo msg : contacts) {
				msg.isSelected = true;
			}
			notifyDataSetChanged();
		}

		public void unCheckedAll() {
			for (ContactInfo msg : contacts) {
				msg.isSelected = false;
			}
			notifyDataSetChanged();
		}

		public int getCount() {
			return contacts.size();
		}

		public ContactInfo getItem(int position) {
			return contacts.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			final ContactInfo contact = contacts.get(position);
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.bu_work_log_get_sys_contact_list_item, null);
				holder = new ViewHolder();
				holder.cust_manager_name = (TextView) convertView.findViewById(R.id.cust_manager_name);
				holder.industry_type_name = (TextView) convertView.findViewById(R.id.industry_type_name);
				holder.phone_no = (TextView) convertView.findViewById(R.id.phone_no);
				holder.select_box = (CheckBox) convertView.findViewById(R.id.select_box);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.cust_manager_name.setText(contact.cust_manager_name);
			holder.industry_type_name.setText(contact.industry_type_name);
			holder.phone_no.setText(contact.phone_no);
			holder.select_box.setTag(contact.phone_no);
			holder.select_box.setChecked(contact.isSelected);

			holder.select_box.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					if (contact.isSelected) {
						contact.isSelected = false;
					} else {
						contact.isSelected = true;
					}
				}
			});
			return convertView;
		}
	}
}
